package com.webserver.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.webserver.servlet.CreateQRCodeServlet;
import com.webserver.servlet.HttpServlet;
import com.webserver.servlet.LoginServlet;
import com.webserver.servlet.RegServlet;
import com.webserver.servlet.UserListServlet;

/**
 * 定义所有服务端相关定义内容
 * @author pc
 *
 */
public class ServerContext {
	/**
	 * 所有请求与对应业务处理类
	 * key:请求路径
	 * value:处理该请求的业务处理类
	 */
	private static Map<String,HttpServlet> servletMapping = new HashMap<>();
	
	static {
		initServletMapping();
	}
	
	private static void initServletMapping() {
//		servletMapping.put("/myweb/reg", new RegServlet());
//		servletMapping.put("/myweb/login", new LoginServlet());
//		servletMapping.put("/myweb/createQR", new CreateQRCodeServlet());
//		servletMapping.put("/myweb/userList", new UserListServlet());
		/*
		 * 解析conf/servlets.xml文件
		 * 将根标签下所有的<servlet>标签获取到，并将其属性path的值作为key
		 * className的值作为value保存到servletMapping这个Map中完成初始化
		 */
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read("./conf/servlets.xml");
			Element root = doc.getRootElement();
			List<Element> list = root.elements("servlet");
			for(Element servletEle : list) {
				String key = servletEle.attributeValue("path");
				String className = servletEle.attributeValue("className");
				System.out.println(key+":"+className);
				Class<?> cls = Class.forName(className);
				HttpServlet o = (HttpServlet)cls.newInstance();
				servletMapping.put(key, o);
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 根据请求路径获取对应的业务处理类
	 * @param path
	 * @return
	 */
	public static HttpServlet getServlet(String path) {
		return servletMapping.get(path);
	}
}









